<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>城市管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>城市管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#cityModal">
            新增城市
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-6">
                <input type="text" id="searchCityName" class="form-control" placeholder="输入城市名称搜索">
            </div>
            <div class="col-md-3">
                <input type="text" id="searchProvince" class="form-control" placeholder="输入省份搜索">
            </div>
            <div class="col-md-3">
                <button class="btn btn-success w-100" onclick="queryCityList(1)">搜索</button>
                <button class="btn btn-light w-100 mt-2" onclick="resetSearch()">重置</button>
            </div>
        </div>
    </div>

    <!-- 城市列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>城市ID</th>
                    <th>城市名称</th>
                    <th>所属省份</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="cityTableBody">
                <tr><td colspan="5" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑城市弹窗 -->
<div class="modal fade" id="cityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增城市</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="cityForm">
                    <input type="hidden" id="cityId">
                    <div class="mb-3">
                        <label for="cityName" class="form-label">城市名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="cityName" required placeholder="请输入城市名称">
                    </div>
                    <div class="mb-3">
                        <label for="province" class="form-label">所属省份 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="province" required placeholder="请输入所属省份">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveCity()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    window.onload = function () {
        queryCityList(currentPage);
    };

    // 查询城市列表
    async function queryCityList(pageNum) {
        try {
            const cityName = document.getElementById("searchCityName").value;
            const province = document.getElementById("searchProvince").value;

            const res = await axios.get("/api/cities/page", {
                params: {
                    pageNum,
                    pageSize,
                    cityName: cityName || undefined,
                    province: province || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("cityTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="5" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(city => {
                const row = `
                        <tr>
                            <td>${city.cityId}</td>
                            <td>${city.cityName}</td>
                            <td>${city.province}</td>
                            <td>${Common.formatDate(city.createTime)}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editCity(${city.cityId})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteCity(${city.cityId})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryCityList);
        } catch (err) {
            Common.errorMsg("查询城市失败：" + err.message);
            document.getElementById("cityTableBody").innerHTML = '<tr><td colspan="5" class="text-center">查询失败</td></tr>';
        }
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById("searchCityName").value = "";
        document.getElementById("searchProvince").value = "";
        queryCityList(1);
    }

    // 编辑城市
    async function editCity(cityId) {
        try {
            const res = await axios.get(`/api/cities/${cityId}`);
            const city = res.data;

            document.getElementById("cityId").value = city.cityId;
            document.getElementById("cityName").value = city.cityName;
            document.getElementById("province").value = city.province;
            document.getElementById("modalTitle").textContent = "编辑城市";

            new bootstrap.Modal(document.getElementById("cityModal")).show();
        } catch (err) {
            Common.errorMsg("加载城市信息失败：" + err.message);
        }
    }

    // 保存城市
    async function saveCity() {
        const cityName = document.getElementById("cityName").value;
        const province = document.getElementById("province").value;
        const cityId = document.getElementById("cityId").value;

        if (!cityName || !province) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        const cityData = {
            cityName,
            province
        };

        try {
            if (cityId) {
                cityData.cityId = parseInt(cityId);
                await axios.put("/api/cities", cityData);
                Common.successMsg("编辑城市成功！");
            } else {
                await axios.post("/api/cities", cityData);
                Common.successMsg("新增城市成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("cityModal")).hide();
            queryCityList(currentPage);
            document.getElementById("cityForm").reset();
            document.getElementById("cityId").value = "";
            document.getElementById("modalTitle").textContent = "新增城市";
        } catch (err) {
            Common.errorMsg("保存城市失败：" + err.message);
        }
    }

    // 删除城市
    function deleteCity(cityId) {
        Common.confirmMsg("确定要删除该城市吗？", async () => {
            try {
                await axios.delete(`/api/cities/${cityId}`);
                Common.successMsg("删除城市成功！");
                queryCityList(currentPage);
            } catch (err) {
                Common.errorMsg("删除城市失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>